package com.xinfang.superminer.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.xinfang.superminer.R;

/**
 * Created by Administrator on 2018/3/27.
 */

public class MyListView extends ListView implements AbsListView.OnScrollListener {

    private View header;//头布局

    private int headerHeight;//头布局自身的高度

    private int scrollState;//当前滚动状态
    private int firstVisibleItem;//当前可见的第一个item
    private int startY;//刚开始触摸屏幕时的Y值

    private int curState = 0;//当前header状态，默认为0
    private final int NORMAL = 0;//正常状态
    private final int PULL = 1;//状态下拉
    private final int RELEASE = 2;//提示刷新状态
    private final int RELEASING = 3;//状态正在刷新

    private boolean canPull = false;//是否可以执行下拉操作

    private refresfListener mListener;//回调接口


    //三个构造方法都要重写
    public MyListView(Context context) {
        super(context);
        initView(context);

    }

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);

    }

    public MyListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);

    }

    //定义回调接口
    public interface refresfListener {
        //page 1返回到首页 0返回到上一页
        void refresh(int page);
    }

    public void setOnRefreshListener(refresfListener listener) {
        this.mListener = listener;
    }


    public void initView(Context context) {

        header = LayoutInflater.from(context).inflate(R.layout.header, null);
        notifyView(header);
        headerHeight = header.getMeasuredHeight();//获取header的高度

        //        headerHeight = header.getHeight();
        paddingTop(-headerHeight);
        //将头布局加进去
        this.addHeaderView(header);

        this.setOnScrollListener(this);
    }


    /**
     * 该方法为通知父布局，子布局view的宽度和高度
     *
     * @param view:子布局
     */
    private void notifyView(View view) {

        ViewGroup.LayoutParams p = view.getLayoutParams();

        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        }

        //spec表示当前子view左右边距,padding表示子view的左右内边距
        //childDimension：子view的宽度
        int width = ViewGroup.getChildMeasureSpec(0, 0, p.width);

        int height;
        int tempHeight = p.height;
        if (tempHeight > 0) {
            //子布局高度不为空，需要填充这个布局
            height = MeasureSpec.makeMeasureSpec(tempHeight, MeasureSpec.EXACTLY);
        } else {
            //高度为0，则不需要填充
            height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        }

        //然后告诉父布局，子布局的高度和宽度
        view.measure(width, height);
    }


    //该方法设定header的paddingTop
    private void paddingTop(int pt) {
        header.setPadding(header.getPaddingLeft(), pt, header.getPaddingRight(), header.getPaddingBottom());
        header.invalidate();
    }


    /***
     * 监听当前滚动状态
     * scrollState：当前滚动状态
     */
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        //记录当前的滚动状态
        this.scrollState = scrollState;

    }

    /***
     * 监听当前滚动的item
     * firstVisibleItem：当前可见的第一个item
     * visibleItemCount：当前共有多少个item可见
     * totalItemCount:总共有多少个item
     */
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {

        this.firstVisibleItem = firstVisibleItem;


    }


    //触屏事件
    public boolean onTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {
            //手指落到屏幕上时
            case MotionEvent.ACTION_DOWN:
                //如果当前可见的第一个item为第0号，说明ListView位于顶端，可以执行下拉刷新
                if (firstVisibleItem == 0) {
                    canPull = true;
                    startY = (int) ev.getY();
                }

                break;
            //手指在屏幕上拖动时
            case MotionEvent.ACTION_MOVE:
                if (canPull) {
                    touchMove(ev);
                }
                break;
            //手指离开屏幕时
            case MotionEvent.ACTION_UP:
                canPull = false;
                if (curState == RELEASE) {
                    curState = RELEASING;
                    refreshHeaderByState();

                } else {
                    curState = NORMAL;
                    refreshHeaderByState();
                    paddingTop(-headerHeight);
                }

                break;
        }

        return super.onTouchEvent(ev);
    }

    /**
     * 该方法根据触摸屏幕滑动来改变STATE，即改变当前状态
     *
     * @param ev
     */
    private void touchMove(MotionEvent ev) {

        int tempY = (int) ev.getY();
        int space = tempY - startY;//移动的距离
        int topdding = space - headerHeight;
        paddingTop(topdding);//即时设定头布局的隐藏高度
        if (space > headerHeight && space < headerHeight + 50 && scrollState == SCROLL_STATE_TOUCH_SCROLL) {
            curState = PULL;//设定为下拉状态
            refreshHeaderByState();
        }
        if (space > headerHeight + 50) {
            curState = RELEASE;//设定为提示刷新状态
            refreshHeaderByState();
        }

        if (space < headerHeight) {
            curState = NORMAL;//设定为正常状态
            refreshHeaderByState();
        }


    }


    /**
     * 根据当前状态更改header的显示界面
     */
    private void refreshHeaderByState() {
//        ProgressBar pb = (ProgressBar) header.findViewById(R.id.progress_bar);
//        ImageView img = (ImageView) header.findViewById(R.id.img_arrow);
//        TextView tv = (TextView) header.findViewById(R.id.textinfo);

        TextView tv_uppage=header.findViewById(R.id.tv_uppage);
        TextView tv_firstpage=header.findViewById(R.id.tv_firstpage);

        tv_uppage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //这里添加刷新数据的逻辑
                mListener.refresh(0);
                //返回上一页
            }
        });
        tv_firstpage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //这里添加刷新数据的逻辑
                mListener.refresh(1);
                //返回首页
            }
        });
        switch (curState) {

            case NORMAL:
//                pb.setVisibility(View.GONE);
//                img.setVisibility(View.VISIBLE);
//                img.setImageResource(R.drawable.down_arrow);
//                tv.setText("下拉刷新");
                break;
            case PULL:
//                pb.setVisibility(View.GONE);
//                img.setVisibility(View.VISIBLE);
//                img.setImageResource(R.drawable.down_arrow);
//                tv.setText("下拉刷新");
                break;
            case RELEASE:
//                pb.setVisibility(View.GONE);
//                img.setVisibility(View.VISIBLE);
//                img.setImageResource(R.drawable.up_arrow);
//                tv.setText("松开刷新");
                break;
            case RELEASING:
//                pb.setVisibility(View.VISIBLE);
//                img.setVisibility(View.GONE);
//                tv.setText("正在刷新");
                break;


        }

    }

    //数据刷新完成后的操作
    public void refreshFinish() {

        curState = NORMAL;
        paddingTop(-headerHeight);
        refreshHeaderByState();
    }


}
